package com.yuyang.wifi.base;


import com.yuyang.wifi.utils.EmptyUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import rx.subjects.PublishSubject;
import rx.subjects.Subject;


/**
 * Created by wangce on 16/1/18.
 */
public class RxBus {

    private static RxBus instance;

    public static  RxBus getInstance(){
        if(null == instance){
            synchronized (RxBus.class) {
                if( null == instance) {
                    instance = new RxBus();
                }
            }
        }
        return instance;
    }


    private RxBus(){

    }


    public <T> SuperSubject<T> register(String tag , Class<T> clazz){
        List<SuperSubject> subjects = subjectMapper.get(tag);
        if(subjects == null){
            subjects = new ArrayList<>();
            subjectMapper.put(tag,subjects);
        }
        Subject<T,T> subject = PublishSubject.create();
        SuperSubject superSubject = new SuperSubject(clazz,subject,tag);
        subjects.add(superSubject);
        return superSubject;
    }


    public void unRegister(SuperSubject superSubject){
        List<SuperSubject> superSubjects = subjectMapper.get(superSubject.getTag());
        if(null != superSubjects){
            superSubjects.remove(superSubject);
            if(EmptyUtils.isEmpty(superSubjects)){
                subjectMapper.remove(superSubjects);
            }
        }
    }


    private Map<String,List<SuperSubject>> subjectMapper = new ConcurrentHashMap<>();
    public void post(String tag , Object event){
        List<SuperSubject> superSubjects = subjectMapper.get(tag);
        if(!EmptyUtils.isEmpty(superSubjects)){
            for (SuperSubject superSubject : superSubjects){
                if(superSubject.getGenericClass().isInstance(event)){
                    superSubject.getSubject().onNext(event);
                }else {
                    new Exception("Type mismatch").printStackTrace();
                }
            }
        }
    }

}
